// pages/main/workorder/process-workorder/process-workorder.js
Page({
  data: {
    workorders: [],
    pendingWorkorders: [], // 待接单工单
    processingWorkorders: [], // 处理中工单
    filteredWorkorders: [],
    loading: true,
    searchKeyword: '',
    activeKey: 'pending', // 当前选中的分类：pending-待接单，processing-处理中
    page: 1,
    pageSize: 20,
    total: 0,
    hasMore: true,
    loadingMore: false,
    error: false,
    errorMessage: ''
  },

  onLoad() {
    this.loadWorkorders();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true,
      workorders: []
    });
    this.loadWorkorders(true);
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loadingMore) {
      this.loadMoreWorkorders();
    }
  },

  // 加载待处理工单
  loadWorkorders(isRefresh = false) {
    if (!isRefresh) {
      this.setData({ loading: true });
    }
    
    const username = wx.getStorageSync('username') || '';
    
    wx.request({
      url: `${getApp().globalData.serverUrl}/GetWorkorderList/`,
      method: 'POST',
        data: {
        list_type: 'process', // 处理记录类型
        username: username,
        status: '', // 不筛选状态，获取所有待处理和处理中的工单
        page: 1,
        page_size: this.data.pageSize
      },
      success: (res) => {
        if (res.data.status) {
          let workorders = res.data.data || [];
          
          // 只显示待处理和处理中的工单
          workorders = workorders.filter(w => 
            w.status === 'pending' || w.status === 'processing'
          );
          
          // 分类工单
          const pendingWorkorders = workorders.filter(w => w.status === 'pending');
          const processingWorkorders = workorders.filter(w => w.status === 'processing');
          
          this.setData({
            workorders: workorders,
            pendingWorkorders: pendingWorkorders,
            processingWorkorders: processingWorkorders,
            total: res.data.total || 0,
            page: 1,
            hasMore: workorders.length < (res.data.total || 0),
            loading: false,
            loadingMore: false,
            error: false,
            errorMessage: ''
          });
          
          // 根据当前分类更新显示列表
          this.updateFilteredWorkorders();
          
          // 应用搜索关键词过滤
          if (this.data.searchKeyword) {
            this.filterWorkorders();
          }
        } else {
          this.setData({
            loading: false,
            error: true,
            errorMessage: res.data.message || '获取工单列表失败'
          });
          wx.showToast({
            title: res.data.message || '获取工单列表失败',
            icon: 'none'
          });
        }
        
        if (isRefresh) {
          wx.stopPullDownRefresh();
        }
      },
      fail: (err) => {
        console.error('获取工单列表失败:', err);
        this.setData({
          loading: false,
          error: true,
          errorMessage: '网络错误，请稍后重试'
        });
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        if (isRefresh) {
          wx.stopPullDownRefresh();
        }
      }
    });
  },

  // 加载更多工单
  loadMoreWorkorders() {
    if (!this.data.hasMore || this.data.loadingMore) {
      return;
    }

    this.setData({ loadingMore: true });
    const username = wx.getStorageSync('username') || '';
    const nextPage = this.data.page + 1;

    wx.request({
      url: `${getApp().globalData.serverUrl}/GetWorkorderList/`,
      method: 'POST',
        data: {
        list_type: 'process',
        username: username,
        status: '', // 不筛选状态，获取所有待处理和处理中的工单
        page: nextPage,
        page_size: this.data.pageSize
      },
      success: (res) => {
        if (res.data.status) {
          let newWorkorders = res.data.data || [];
          
          // 只显示待处理和处理中的工单
          newWorkorders = newWorkorders.filter(w => 
            w.status === 'pending' || w.status === 'processing'
          );
          
          const allWorkorders = [...this.data.workorders, ...newWorkorders];
          
          // 分类工单
          const pendingWorkorders = allWorkorders.filter(w => w.status === 'pending');
          const processingWorkorders = allWorkorders.filter(w => w.status === 'processing');
          
          this.setData({
            workorders: allWorkorders,
            pendingWorkorders: pendingWorkorders,
            processingWorkorders: processingWorkorders,
            page: nextPage,
            hasMore: allWorkorders.length < (res.data.total || 0),
            loadingMore: false
          });
          
          // 根据当前分类更新显示列表
          this.updateFilteredWorkorders();
          
          // 应用搜索关键词过滤
          if (this.data.searchKeyword) {
            this.filterWorkorders();
          }
        } else {
          this.setData({ loadingMore: false });
          wx.showToast({
            title: res.data.message || '加载更多失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('加载更多失败:', err);
        this.setData({ loadingMore: false });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 搜索输入变化
  onSearchChange(e) {
    const keyword = e.detail.value || '';
    this.setData({ searchKeyword: keyword });
    this.filterWorkorders();
  },

  // 搜索确认
  onSearchConfirm(e) {
    const keyword = e.detail.value || '';
    this.setData({ searchKeyword: keyword });
    this.filterWorkorders();
  },

  // 清除搜索
  onSearchClear() {
    this.setData({ 
      searchKeyword: ''
    });
    this.updateFilteredWorkorders();
  },

  // 取消搜索
  onSearchCancel() {
    this.setData({ 
      searchKeyword: ''
    });
    this.updateFilteredWorkorders();
  },

  // 过滤工单（根据搜索关键词）
  filterWorkorders() {
    const keyword = this.data.searchKeyword.toLowerCase().trim();
    if (!keyword) {
      this.updateFilteredWorkorders();
      return;
    }

    const currentList = this.data.activeKey === 'pending'
      ? this.data.pendingWorkorders 
      : this.data.processingWorkorders;

    const filtered = currentList.filter(workorder => {
      return (
        (workorder.workorder_number && workorder.workorder_number.toLowerCase().includes(keyword)) ||
        (workorder.type_name && workorder.type_name.includes(keyword)) ||
        (workorder.content && workorder.content.includes(keyword)) ||
        (workorder.location && workorder.location.includes(keyword)) ||
        (workorder.username && workorder.username.includes(keyword))
      );
    });

    this.setData({ filteredWorkorders: filtered });
  },

  // 分类切换
  onTabChange(e) {
    const activeKey = e.detail.activeKey;
    this.setData({ 
      activeKey: activeKey,
      searchKeyword: '' // 切换分类时清空搜索
    });
    this.updateFilteredWorkorders();
  },

  // 更新过滤后的工单列表
  updateFilteredWorkorders() {
    const workorders = this.data.activeKey === 'pending'
      ? this.data.pendingWorkorders 
      : this.data.processingWorkorders;
    this.setData({ filteredWorkorders: workorders });
  },

  // 点击工单项
  onWorkorderTap(e) {
    const workorder = e.currentTarget.dataset.workorder;
    // 跳转到详情页面
    wx.navigateTo({
      url: `/pages/main/workorder/workorder-detail/workorder-detail?id=${workorder.id}&source=process-workorder`
    });
  },

  // 重试加载
  onRetry() {
    this.setData({
      error: false,
      errorMessage: '',
      page: 1,
      hasMore: true
    });
    this.loadWorkorders();
  }
});
